/**
 * Created by pankajmishra on 26/01/15.
 */
define(['jquery','mustache','peer.min','module/home/customEvent'
,'module/template/homeTemplate'], function($,mustache,peer, customEvent, template){

    var peer = new Peer({key: 't6gcqn9c9yqtzkt9'}), chatWinCount = 0, userMap = {}, you, initialBodyHeight;

    window.onunload = window.onbeforeunload = function(e) {
        if (!!peer && !peer.destroyed) {
            peer.destroy();
        }
    };

    function handleData(data){
        receive( data.txt, data.id);
    }

    function handleError(err){
        console.log(err);
    }

    peer.on('connection', function(dataConnection) {
        dataConnection.on('data', handleData);
        dataConnection.on('error', handleError);
    });


    // get user;
    (function(){
        $.getJSON('/user/getMe').
            done(function(data){
                you = data;
            });
    })();

    function getLoggedinUser() {
        $.getJSON('/people/getLoggedIn').
            done(function(data){

                var dataToSend = [], uids = [];
                $.each(data, function(index, user){
                    uids.push(user.id + '');
                    if(user.id in userMap){

                    } else {
                        dataToSend.push({u:user, add : true});
                    }
                    userMap[user.id] = user;
                });

                $.each(userMap, function(key, val){
                    if(/win$/.test(key) || /dc$/.test(key)){

                    } else if(uids.indexOf(key) < 0 ) {
                        dataToSend.push({u:userMap[key], remove : true});
                        delete userMap[getDataConnectionKey(key, getChatIdOfUser(key))];
                        delete userMap[getWindowConnectionKey(key)];
                        delete userMap[key];
                    }
                });

                if(dataToSend.length > 0){
                    $.event.trigger({
                        type: customEvent.GET_LOGGED_USERS,
                        loggedInUser: dataToSend
                    });
                }
                setTimeout(getLoggedinUser, 30000);
            });
    }

    function getDataConnectionKey(userId, chatId){
        return userId + '_dc_' + chatId;
    }

    function getWindowConnectionKey(userId){
        return userId + '_win'
    }

    function getChatIdOfUser(userID){
        return userMap[userID].chatID;
    }


    function insertIntoChatWindow(obj, chatWindow) {
        obj['user'] = userMap[obj['id']];
        chatWindow.find('.body').append($( mustache.render(template['people-chat-item'], obj)));
        adjustScroll(chatWindow);
    }

    function insertIntoChatWindowAsYou(obj, chatWindow) {
        obj['user'] = you;
        chatWindow.find('.body').append($( mustache.render(template['people-chatme-item'], obj)));

        var conKey = getDataConnectionKey(obj['to'].id, getChatIdOfUser(obj['to'].id));
        if(conKey in userMap){
            send( obj.txt, userMap[conKey] , obj['to'].id);
        } else {
            userMap[ conKey ] = connectAndSend(getChatIdOfUser(obj['to'].id), obj.txt ,obj['to'].id);
        }
        adjustScroll(chatWindow);
    }


    function adjustScroll(chatWindow){
       var body =   chatWindow.find('.body');
        if(body.outerHeight()  - initialBodyHeight > 0)
            body.parent().scrollTop((body.outerHeight() + 150)  - initialBodyHeight);
    }

    function createChatWindow(user){
        var chatWindow =  $( mustache.render(template['people-chat-window'], user));
        $('.js_abs').append(chatWindow);
        var left = 30 + (chatWindow.outerWidth() + 20 ) * chatWinCount;
        chatWindow.css('left',left);
        ++chatWinCount;
        chatWindow.find('span.remove').on('click', function(){
            destroyChatWindow(chatWindow);
            delete userMap[getWindowConnectionKey(user.id)];
        });
        initialBodyHeight = chatWindow.find('.body').outerHeight();
        userMap[getWindowConnectionKey(user.id)] = chatWindow;
        chatWindow.find('input[type="text"]').on('keydown', function(event){
            if(event.keyCode == 13){
                insertIntoChatWindowAsYou({txt:$(this).val(), id:you.id, to : user}, chatWindow);
                $(this).val('');
            }
        });

        getChat(chatWindow, user.id, you.id);

        $(document).on('scroll', function(){chatWindow.css('bottom', '0' )});

        // bot chatting.
/*
        setInterval(function(){
            insertIntoChatWindow({txt:'test ... ', id:user.id},chatWindow );
        }, 10000);
*/
        // bot chatting end

        return chatWindow;
    }

    function destroyChatWindow(chatDom){
        chatDom.remove();
        --chatWinCount;
    }


    setTimeout(getLoggedinUser, 10000);

    function getUser(userId, userMap){
        return userMap[userId];
    }


    function addEvent(dom){
        dom.find('a').on('click',function(){
            createWinIfReq($(this).data('user'));
        });
    }

    function createWinIfReq(userId){
        if(getWindowConnectionKey(userId) in userMap){
        } else {
            createChatWindow ( getUser (userId, userMap) );
        }
    }

    function saveChat(from, to, str){
        $.post( '/people/saveChat', {from:from, to:to, chat : str}).done(function(){});
    }

    function getChat(chatWindow, one, second){
        $.getJSON('/people/getChat',{one : one, second : second}).
            done(function(data){
                $.each(data, function(index, chati){

                    var templateName = chati.id == you.id ? 'people-chatme-item' : 'people-chat-item';

                    chatWindow.find('.body').find('.his').append($( mustache.render(template[templateName],
                        {
                            user : {name: chati.name, photoarray : chati.photoarray},
                            txt : chati.chat,
                            insert_time : chati.insert_time
                        })));
                });
            });
    }

    function receive(chatStr, userId){
        createWinIfReq(userId);
        insertIntoChatWindow( {txt: chatStr, id : userId}, userMap[getWindowConnectionKey(userId)]);
        saveChat(userId, you.id, chatStr);
    }

    function connectAndSend(id, str, toUser){
        var dataConnection = peer.connect(id, {serialization: 'json'});
        dataConnection.on('open', function(){
            dataConnection.send({txt:str, id :you.id});
          //  saveChat(you.id, toUser, str);
        });
        dataConnection.on('data', handleData);
        dataConnection.on('error', handleError);
        return dataConnection;
    }

    function send(str, dataConnection, toUser){
        dataConnection.send({txt : str, id : you.id});
      //  saveChat(you.id, toUser, str);
    }

    return {
        initialize : function(){
            peer.on('open', function(ID){
                $.post( '/people/saveUser', {chatId:ID}).done(function(){});
            })
        },
        send : connectAndSend,
        create : createChatWindow,
        addEvent : addEvent
    };

});